<template>
  <el-dialog :title="$tt('label_logistics_division_config')" :visible.sync="visible" custom-class="dialog_big">
    <el-form ref="form" v-loading="loading" :model="form" :rules="rules">
      <div class="flex_row mg_b1" style="align-items: center;">
        <el-button icon="el-icon-plus" @click="addNew" v-if="!disabled">
          {{ $tt('label_logistics_division') }}
        </el-button>
        <button_select_file @input="selectFile" v-if="sourceType==='product'">
          {{$t('label_partition_restriction_import')}}
          <i class="el-icon-upload2 el-icon--right"></i>
        </button_select_file>
        <el-button @click="downloadImportTemp" size="mini" type="primary" v-if="sourceType==='product'">
            {{ $tt('label_download_import_template') }}<i class="el-icon-download el-icon--right"></i>
          </el-button>
        <div class="mg_h2">
          {{ $tt('label_current_select_country') }}：
          <span class="bold">
            {{ countryList.map(it => $formatNameCode(it.countryName, it.countryCode)).join() }}</span>
        </div>


      </div>
      <ex_super_table ref="MainTable" :data="form.tableData" v-bind="table" @selection-change="e => selection = e">
        <template v-slot:postalCodeArea_header="{ model }">
          <div class="flex_row" style="display: inline-flex;">
            {{ $tt(model.label) }}
            <el-tooltip placement="top" effect="light">
              <div slot="content" style="line-height: 28px; " v-html="$tt('html_tip_transport_area_edit')">
              </div>
              <el-button type="text" class="el-icon-question"></el-button>
            </el-tooltip>
          </div>

        </template>
        <template v-slot:sort_header="{ model }">
          {{ $tt(model.label) }}
            <el-tooltip placement="top" effect="light">
              <div slot="content" style="line-height: 28px; " v-html="$tt('tip_transport_area_edit_sort')">
              </div>
              <el-button type="text" class="el-icon-question"></el-button>
            </el-tooltip>
        </template>
      </ex_super_table>

      <div class="dialog-footer">
        <el-button @click="visible = false">{{ $tt('label_cancel') }}</el-button>
        <el-button type="primary" @click="submitBeforeTip()" v-if="!disabled">{{ $tt('label_confirm') }}</el-button>
      </div>
    </el-form>

  </el-dialog>
</template>

<script>

import ExcelJS from '@/asset/exceljs.bare.min.js'
const default_obj = {
  edit: false,
  subareaName: "",
  postalCodeArea: "",
  groupCode: "",
  maxWeight:"",
  minVolume:"",
  maxVolume:"",
  maxBorder:"",
  maxEdgeLength:"",
  postcodeMatchCondition:"INCLUDE",
  sort:0
}
export default {
  data() {

    return {
      selection: [],
      countryList: [],

      visible: false,
      loading: false,
      form: {
        tableData: [],

      },
      rules: {
        countryCode: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, },

        groupCode: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, },
        subareaName: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, },

        postalCodeArea: { type: 'string', message: this.$tt('tip_can_no_empty'), required: true, },

      },
      table: {
        'height': 500,
        model: [
          {
            type: 'selection',
            // clickToggle: true,
            clickExclude: ["groupCode", "subareaName", "postalCodeArea", 'countryCode'],
            selectable: (row, i) => !this.disabled
          },
          {
            key: 'countryCode', label: 'label_country', 'width': 150,
            "label-class-name": "label_require_before",
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const isnew = row.new
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <ex_select_auto disabled={!isnew} value={value} onChangeItem={e => {
                    this.$set(row, key, e[key])
                    this.$set(row, "countryName", e["countryName"])
                  }}
                    items={this.countryList} option={{ label: "countryName", value: "countryCode" }}
                  />
                </el-form-item>
              );
            }
          },
          {
            key: 'groupCode', label: 'label_zonal_coding', 'width': 140,
            "label-class-name": "label_require_before",
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('label_zonal_coding')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'subareaName', label: 'label_logistics_division_name', 'width': 140,
            "label-class-name": "label_require_before",
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('label_logistics_division_name')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'postalCodeArea', label: 'label_postCode_match_rule',
            'min-width': 400,
            "label-class-name": "label_require_before",
            slot_header: 'postalCodeArea_header',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              const postcodeMatchCondition = this.sourceType==='product'? <ex_super_input value={row.postcodeMatchCondition} disabled={!edit} type="select" enum="PostcodeMatchConditionEnum" onInput={e => this.$set(row, 'postcodeMatchCondition', e)}/> : ''
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <div style="display:flex;gap:10px">
                    <el-input disabled={!edit} type="textarea" value={value} autosize onInput={e => this.$set(row, key, e)} placeholder={this.$tt('label_postCode_match_rule')}></el-input>
                    {postcodeMatchCondition}
                  </div>
                </el-form-item>
              );
            }
          },
          {
            key: 'sort',
            label: this.$t('label_sort_index',['(KG)']),
            slot_header: 'sort_header',
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'minWeight',
            label: this.$t('label_pms_min_weight_unit',['(KG)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'maxWeight',
            label: this.$t('label_pms_max_weight_unit',['(KG)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'minVolume',
            label: this.$t('label_pms_min_volume_unit',['(cbm)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'maxVolume',
            label: this.$t('label_pms_max_volume_unit',['(cbm)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'maxBorder',
            label: this.$t('label_pms_max_border_unit',['(cm)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            key: 'maxEdgeLength',
            label: this.$t('label_pms_max_edge_length_unit',['(cm)']),
            'width': 140,
            if: () => this.sourceType === 'product',
            render: (h, { row, column, index }) => {
              const key = column.property
              const value = row[key]
              const edit = row.edit
              return (
                <el-form-item
                  prop={`tableData.${index}.${key}`}
                  rules={this.rules[key]}
                >
                  <el-input disabled={!edit} value={value} onInput={e => this.$set(row, key, e)} clearable placeholder={this.$tt('tip_please_input')}></el-input>
                </el-form-item>
              );
            }
          },
          {
            type: 'operate', width: 160, operate: [
              {
                label: 'label_edit', if: (row) => !row.edit && !this.disabled, click: (row, i, list) => {
                  this.editRow(row)
                }
              },
              {
                label: 'label_save', if: (row) => row.edit && !this.disabled, click: (row, i, list) => {
                  this.saveRow(row, i)
                }
              },
              {
                label: 'label_cancel', if: (row) => row.edit && !this.disabled, buttonClass: "button_text_warning", click: (row, i, list) => {
                  this.cancelRow(row, i, list)
                }
              },
              {
                label: 'label_delete', if: (row) => row.id && !row.edit && !this.disabled, type: "confirm-button", buttonClass: "button_text_danger", confirmButtonType: 'danger',

                url: '/tms-api/base/TmsLogisticsAreaInfoRpc/deleteById.json', message: 'text_confirm_sure_delete',
                params: (v) => { return { id: v.id } }, done: (row, i, data, res) => {
                  data.splice(i, 1)
                }
              }
            ]
          }
        ]
      },
    }
  },

  props: {
    // 已选中的分区id
    disabled: {
      type: Boolean,
      default: false,
    },
    areaIds: {
      "type": Array,
      "default": () => { return [] }
    },
    countryCode: String,
    countryName: String,
    sourceType: {
      type: String,
      default: '',
    },

    // countryCodeList: {
    //   "type": Array,
    //   "default": ()=>{ return []}
    // },

  },
  methods: {
    addNew() {
      const item = _.cloneDeep(default_obj)
      item.new = true
      item.edit = true
      item.postcodeMatchCondition =item.postcodeMatchCondition||'INCLUDE'

      item.sort=item.sort||0
      // item.countryName = this.countryName
      // item.countryCode = this.countryCode
      this.form.tableData.push(item)
    },

    delete(item, i, list) {
      if (item.id) {
        this.$ajax({
          url: "/tms-api/base/TmsLogisticsAreaInfoRpc/deleteById.json",
          method: 'post',
          data: {
            id: item.id
          },
          loading: true,
          success: (res) => {
            list.splice(i, 1)
          },
          complete: () => {

          }
        })
      } else {
        list.splice(i, 1)
      }

    },
    getCountryList({ success }) {

      this.$ajax({
        url: "/tms-api/base/TmsCountryRpc/selectCountry.json",
        type: 'json',
        data: {
          countryCodeList: [this.countryCode],
        },
        success: (res) => {
          if (res.data && res.data.rows && !_.isEmpty(res.data.rows)) {
            const item = _.find(res.data.rows, it => it.countryCode == this.countryCode)
            if (item) {
              if (item.tmsCountryType == 'GROUPE') {
                this.countryList = item.tmsCountryChildList
              } else {
                this.countryList = [item]
              }
              success(this.countryList)
              return
            }
          }
          this.loading = false
          return this.$message.error(this.$tt("tip_country_search_fail"))
        },
        failure: () => {
          this.loading = false

        },
        complete: () => {
        }
      })
    },
    show(areaLimitConfigList='') {

      if (!this.countryCode || !this.countryName) {
        return this.$message.warning(this.$tt("tip_please_select_country"))
      }
      this.visible = true
      this.loading = true
      this.form.tableData = []
      this.getCountryList({
        success: (countryList) => {
          this.loading = true
          this.$ajax({
            url: "/tms-api/base/TmsLogisticsAreaInfoRpc/selectLabel.json",
            method: 'post',
            type: 'json',
            data: {
              countryCode: this.countryCode,
              countryCodeList: countryList.map(it => it.countryCode),
              // logisticsSubIdList: this.areaIds,
            },
            success: (res) => {
              if (res.data && res.data.rows) {
                this.form.tableData = res.data.rows.map(it => {
                  it.edit = false
                  return it
                })
                if (_.isEmpty(this.form.tableData)) this.addNew()
                // 勾选
                if (!_.isEmpty(this.areaIds)) {
                  this.$nextTick(() => {
                    if (this.$refs.MainTable) {
                      this.areaIds.forEach(id => {
                        let item = _.find(this.form.tableData, it => it.id == id)
                        if (item) {
                          this.$refs.MainTable.toggleRowSelection(item, true)
                        }
                      })
                    }
                  })
                }

                // 填充物流产品设置的数据
                if (!_.isEmpty(areaLimitConfigList)) {
                  for (let index = 0; index < this.form.tableData.length; index++) {
                    const item = this.form.tableData[index];
                    for (let index2 = 0; index2 < areaLimitConfigList.length; index2++) {
                      const item2 = areaLimitConfigList[index2];
                      if(item.id===item2.areaId){
                        this.setTableData(index,item2)
                        break
                      }
                    }
                  }
                }
              }
            },
            complete: () => {
              this.loading = false
            }
          })
        }
      })




    },
    save(item) {

      this.loading = true
      this.$ajax({
        url: "/tms-api/base/TmsLogisticsAreaInfoRpc/saveOrUpdate.json",
        method: 'post', type: 'json',
        data: {
          logisticsSubareaInfoParamList: [item]
        },
        success: (res) => {
          if (res.data && res.data.rows) {
            let itemData = _.head(res.data.rows)
            if (itemData) {
              item.id = itemData.id

              delete item.new
              delete item.back
              item.edit = false
            }
          }

        },
        complete: () => {
          this.loading = false
        }
      })
    },
    saveRow(row, index, checkMethodName) {
      this.$formRulesValidate({
        formRef: this.$refs.form,
        rules: this.rules,
        props: _.keys(this.rules).map(it => `tableData.${index}.${it}`),
        success: () => {
          // console.log("ok")
          this.save(row)
        }
      })
      // if (this[checkMethodName](row, i)) {
      //   this.save(row)
      // }


    },
    editRow(row) {
      let back = _.clone(row)
      row.back = back
      this.$set(row, 'edit', true)
    },
    cancelRow(row, i, list) {
      if (row.new) {
        list.splice(i, 1)
      } else {
        list.splice(i, 1, row.back)
      }
    },
    deleteRow(row, i, list) {
      list.splice(i, 1)
    },
    submitBeforeTip() {
      if (this.form.tableData.some(it => it.edit)) {
        this.$confirm(this.$t('tip_has_no_save_detail_confrim_submit'), this.$t('label_tip'), {
          type: 'warning'
        }).then(() => {
          this.form.tableData.forEach((row, i) => {
            if (row.edit) this.cancelRow(row, i, this.form.tableData)
          })
          this.submit()
        }).catch(() => {
        });
      } else {
        this.submitForm()
      }
    },

    getSelection() {
      return this.selection
    },

    submitForm() {
      this.visible = false
      //console.log(this.selection)
      this.$emit("afterSubmitSuccess", this.selection)
    },
    // 物流分区限制导入
    selectFile(e) {
      if (!e || e.length == 0) return
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      let reader = new FileReader();
      reader.onload = (e) => {
        const data = e.target.result
        new ExcelJS.Workbook().xlsx.load(data).then(workbook => {
          if (workbook._worksheets[1]) {
            const excelData = []
            const worksheet = workbook.getWorksheet(1);
            worksheet.eachRow((row, rowNumber) => {
              excelData.push(row.values)
            });
            if (excelData.length == 0) return this.$message.error(this.$t('label_import_error'))
            this.excelDatahand(excelData)
          }
        })
      };
      loading.close();
      reader.readAsArrayBuffer(e[0]);
    },
    excelDatahand(metadata){
      metadata.forEach(row=>{
        for (let index = 0; index < this.form.tableData.length; index++) {
          const item = this.form.tableData[index];
          if(row[1]===item.groupCode){
            const data = {
              minWeight:row[3],
              maxWeight:row[4],
              minVolume:row[5],
              maxVolume:row[6],
              maxBorder:row[7],
              maxEdgeLength:row[8],
            }
            this.setTableData(index,data)
            break
          }
        }
      })
    },
    // 导入 或 编辑回显 设置数据
    setTableData(index,item){
      this.$set(this.form.tableData[index],'minWeight',item.minWeight)
      this.$set(this.form.tableData[index],'maxWeight',item.maxWeight)
      this.$set(this.form.tableData[index],'minVolume',item.minVolume)
      this.$set(this.form.tableData[index],'maxVolume',item.maxVolume)
      this.$set(this.form.tableData[index],'maxBorder',item.maxBorder)
      this.$set(this.form.tableData[index],'maxEdgeLength',item.maxEdgeLength)
    },
    // 下载模版
    downloadImportTemp() {
      window.open('http://kyb-bronze-public-oss.oss-cn-shenzhen.aliyuncs.com/default_template/area_import_1.xlsx')
    }
  }
}
</script>

<style></style>
